package com.atguigu.bigdata.chapter09;

import com.atguigu.bigdata.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.functions.PatternProcessFunction;
import org.apache.flink.cep.functions.TimedOutPartialMatchHandler;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.List;
import java.util.Map;

/**
 * @Author lzc
 * @Date 2022/9/8 15:02
 */
public class Flink10_CEP_Process {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        // 1. 先有流: 流必须要设置事件时间和水印
        SingleOutputStreamOperator<WaterSensor> stream = env
            .readTextFile("input/sensor.txt")
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(
                    data[0],
                    Long.valueOf(data[1]),
                    Integer.valueOf(data[2])
                );
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forMonotonousTimestamps()
                    .withTimestampAssigner((ws, ts) -> ws.getTs())
            );
        
        // 2. 定义规则(模式) 类似正则表达式
        Pattern<WaterSensor, WaterSensor> pattern =
            Pattern
                .<WaterSensor>begin("s1")
                .where(new SimpleCondition<WaterSensor>() {
                    @Override
                    public boolean filter(WaterSensor value) throws Exception {
                        return "sensor_1".equals(value.getId());
                    }
                })
                .next("s2")
                .where(new SimpleCondition<WaterSensor>() {
                    @Override
                    public boolean filter(WaterSensor value) throws Exception {
                        return "sensor_2".equals(value.getId());
                    }
                })
                .within(Time.seconds(2)); // 定义模式的有效期: 小于2s, 不包括2s(换句话说, 如果正好2s也是超过了有效期)
        
        
        // 3. 把规则作用到流上, 得到一个模式流
        PatternStream<WaterSensor> ps = CEP.pattern(stream, pattern);
        
        // 4. 从模式流中取出匹配到的数据
        
        SingleOutputStreamOperator<String> normal = ps
            .process(new MyPatternProcessFunction());
        
        
        normal.print("正常");
        normal.getSideOutput(new OutputTag<String>("timeout") {}).print("timeout");
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    public static class MyPatternProcessFunction extends PatternProcessFunction<WaterSensor, String>
        implements TimedOutPartialMatchHandler<WaterSensor> {
        // 这个方法是继承自:PatternProcessFunction
        // 处理匹配成功的数据
        @Override
        public void processMatch(Map<String, List<WaterSensor>> map,
                                 Context ctx,
                                 Collector<String> out) throws Exception {
            out.collect(map.toString());
            
        }
        
        // 来源于TimedOutPartialMatchHandler
        // 用来处理超时数据的
        @Override
        public void processTimedOutMatch(Map<String, List<WaterSensor>> map,
                                         Context ctx) throws Exception {
            // 把超时数据写出到侧输出流中
            ctx.output(new OutputTag<String>("timeout") {}, map.toString());
        }
    }
}
/*
cep中数据有3种:

1. 匹配成功的数据
    可以获取到

2. 超时的数据
    可以获取到

3. 没有匹配成功的数据
    直接丢弃, 没有办法获取到


 */